package com.gwsdk.paysdk.acitvityV2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwsdk.mqtt.ServiceUtils;
import com.gwsdk.paysdk.bean.LoginModel;
import com.gwsdk.paysdk.bean.privacy.PrivacyManager;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.dialog.GWTipDialog;
import com.gwsdk.paysdk.entity.UserLogin;
import com.gwsdk.paysdk.http.process.CodeProcess;
import com.gwsdk.paysdk.http.process.LoginProcess;
import com.gwsdk.paysdk.manager.GWGameManager;
import com.gwsdk.paysdk.manager.GWMqttManager;
import com.gwsdk.paysdk.service.MqttService;
import com.gwsdk.paysdk.utils.AppStatus;
import com.gwsdk.paysdk.utils.AppStatusManager;
import com.gwsdk.paysdk.utils.AppUtils;
import com.gwsdk.paysdk.utils.GWInflaterUtils;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.NoDoubleClickListener;
import com.gwsdk.paysdk.utils.SharedPreferencesUtils;
import com.gwsdk.paysdk.utils.TextUtils;
import com.gwsdk.paysdk.utils.ToastUtil;
import com.gwsdk.paysdk.utils.WebViewUtil;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GWLoginActivity extends GWBaseActivity {


    private static final String TAG = "GWLoginActivity";
    private TextView phoneTV;
    private TextView codeTV;
    private TextView getCodeBtn;
    private TextView submitBtn;
    private TextView agreementBtn;
    private TextView protoalBtn;
    private Boolean isAutoLogin = false;
    private GWTipDialog mcTipDialog;
    private Boolean isLogining = false;
    private Boolean checkbox = true;
    private TextView authLogin,phoneLogin;
    private View authLoginView,phoneLoginView;
    private GWAuthLoginBroadcastReceiver authLoginBroadcastReceiver;
    private ImageView checkboxImageView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏 
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏(主要功能就是去除页面弹出时顶部黑色条)

        if(AppStatusManager.getInstance().getAppStatus() == AppStatus.STATUS_RECYVLE){
            Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            finish();
        }

        ServiceUtils.stopService(MqttService.class);
        MqttService.closeConnection();

        ComeOutType();
        super.onCreate(savedInstanceState);

        isAutoLogin = getIntent().getBooleanExtra("isAutoLogin",false);
        setContentView(GWInflaterUtils.getLayout(this,"gw_activity_login"));
        if (isAutoLogin){
            View view = new View(this);
            view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
            setContentView(view);
            String phone = getIntent().getStringExtra("phone");
            String userId = getIntent().getStringExtra("user_id");
            startUserLogin(phone,userId);
        }else {
            initView();
        }
        authLoginBroadcastReceiver = new GWAuthLoginBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.gwwan.com.auth.login");
        filter.addAction("openBoxLoginNotification");
        registerReceiver(authLoginBroadcastReceiver, filter);

    }



    @Override
    protected void onPause() {
        super.onPause();

    }


    private boolean isResisterBroadcast = false;
    private void initView(){

        phoneTV = findViewById(GWInflaterUtils.getControl(this,"edit_phone"));
        codeTV = findViewById(GWInflaterUtils.getControl(this,"edit_code"));
        getCodeBtn = findViewById(GWInflaterUtils.getControl(this,"btn_get_code"));
        submitBtn = findViewById(GWInflaterUtils.getControl(this,"submit_login"));
        authLogin = findViewById(GWInflaterUtils.getControl(this,"auth_login"));
        phoneLogin = findViewById(GWInflaterUtils.getControl(this,"phone_login"));
        authLoginView = findViewById(GWInflaterUtils.getControl(this,"auth_login_view"));
        phoneLoginView = findViewById(GWInflaterUtils.getControl(this,"phone_login_view"));
        checkboxImageView = findViewById(GWInflaterUtils.getControl(this,"checkbox"));
        getCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCodeEvent();
            }
        });
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitEvent();
            }
        });
        agreementBtn = findViewById(GWInflaterUtils.getControl(this,"txt_btn_agreement"));
        protoalBtn = findViewById(GWInflaterUtils.getControl(this,"txt_btn_protoal"));
        agreementBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAgreement();
            }
        });

        setLoginStatus();

        checkboxImageView.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                checkbox = !checkbox;
                if (checkbox){

                    checkboxImageView.setImageResource(GWInflaterUtils.getDrawable(GWLoginActivity.this,"xieyi_select"));
                }else {
                    checkboxImageView.setImageResource(GWInflaterUtils.getDrawable(GWLoginActivity.this,"xieyi"));
                }
            }
        });

        authLogin.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                authLogin.setTextColor(Color.parseColor("#14B6FC"));
                phoneLogin.setTextColor(Color.parseColor("#E4E4E4"));
                authLoginView.setVisibility(View.VISIBLE);
                phoneLoginView.setVisibility(View.GONE);
            }
        });

        phoneLogin.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                phoneLogin.setTextColor(Color.parseColor("#14B6FC"));
                authLogin.setTextColor(Color.parseColor("#E4E4E4"));
                phoneLoginView.setVisibility(View.VISIBLE);
                authLoginView.setVisibility(View.GONE);
            }
        });

        findViewById(GWInflaterUtils.getControl(this,"gw_app_submit_login")).setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                authLoginAction();
            }
        });

        protoalBtn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                showUserProtoal();
            }
        });
    }

    private void setLoginStatus(){
        if (AppStatusManager.getInstance().openBoxLogin){
            authLogin.setVisibility(View.VISIBLE);
            if (AppUtils.checkAppInstalled(this,"com.genwan.voice")){
                authLogin.setTextColor(Color.parseColor("#14B6FC"));
                phoneLogin.setTextColor(Color.parseColor("#E4E4E4"));
                authLoginView.setVisibility(View.VISIBLE);
                phoneLoginView.setVisibility(View.GONE);
            }else {
                phoneLogin.setTextColor(Color.parseColor("#14B6FC"));
                authLogin.setTextColor(Color.parseColor("#E4E4E4"));
                phoneLoginView.setVisibility(View.VISIBLE);
                authLoginView.setVisibility(View.GONE);
            }

        }else {
            authLoginView.setVisibility(View.GONE);
            authLogin.setVisibility(View.GONE);
            phoneLoginView.setVisibility(View.VISIBLE);
            phoneLogin.setTextColor(Color.parseColor("#14B6FC"));
        }
    }
    private long lastJumpAppTime = 0;
    private void authLoginAction(){
        if (!checkbox){
            ToastUtil.show(GWLoginActivity.this, "请先同意用户协议和隐私政策");
            return;
        }
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastJumpAppTime < 1000) {
            lastJumpAppTime = currentTime;
            return;
        }
        if (AppUtils.checkAppInstalled(this,"com.genwan.voice")){
            Bundle bundle = new Bundle();
            bundle.putInt("type",1);
            bundle.putString("className","com.gwsdk.paysdk.acitvityV2.GWAuthLoginActivity");
            AppUtils.jumpAPP(this,"com.genwan.voice",bundle);
        }else {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(AppStatusManager.getInstance().downUrl);
            intent.setData(content_url);
            startActivity(intent);
        }

    }

    private void showUserProtoal(){
        WebViewUtil.webView(this, PrivacyManager.getInstance().privacyUrl(), true);
    }

    private void showAgreement(){
        WebViewUtil.webView(this, PrivacyManager.getInstance().agreeUrl(), true);
    }

    CountDownTimer downTimer;
    private void getCodeEvent(){

        if (!checkbox){
            ToastUtil.show(GWLoginActivity.this, "请先同意用户协议和隐私政策");
            return;
        }

        String phone = phoneTV.getText().toString();

        if (phone.length() <= 0){
            ToastUtil.show("手机号不能为空");
            return;
        }
        if (phone.length() < 11){
            ToastUtil.show("请输入11位手机号码");
            return;
        }
        mcTipDialog = new GWTipDialog.Builder().setMessage("发送验证码中...").show(this,getFragmentManager());
        getCodeBtn.setBackgroundResource(GWInflaterUtils.getDrawable(this,"gw_disable_btn_bg"));//getResources().getDrawable(R.drawable.gw_disable_btn_bg));
        getCodeBtn.setTextColor(Color.parseColor("#666666"));
        getCodeBtn.setEnabled(false);
        CodeProcess codeProcess = new CodeProcess(this);
        codeProcess.setPhone(phone);
        codeProcess.post(getCodeHeader);
    }

    private void submitEvent(){
        if (isLogining) return;
        if (!checkbox){
            ToastUtil.show(GWLoginActivity.this, "请先同意用户协议和隐私政策");
            return;
        }
        String phone = phoneTV.getText().toString();
        String code = codeTV.getText().toString();
        if (checkLogin(phone, code)) {
            isLogining = true;
            submitBtn.setEnabled(false);
            submitBtn.setText("正在登入中...");
            LoginProcess loginprocess = new LoginProcess(this);
            loginprocess.setAccount(phone);
            loginprocess.setPassword(code);
            loginprocess.post(loginHandle);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private boolean login = false;
    public class GWAuthLoginBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if ("com.gwwan.com.auth.login".equals(intent.getAction())){
                if (!login){
                    login = true;
                    String phone = intent.getStringExtra("phone");
                    String userId = intent.getStringExtra("userId");
                    startUserLogin(phone,userId);
                }
            }else if ("com.gwwan.com.boxLoginStatus".equals(intent.getAction())){
                setLoginStatus();
            }
        }
    }
    /**
     * 自动登录开始登陆
     * @param userId  userId
     */
    public void startUserLogin(String phone, String userId) {
        GWLog.w(TAG, "phone = " + phone);
        LoginProcess loginprocess = new LoginProcess(this);
        loginprocess.setAccount(phone);
        loginprocess.setUserId(userId);
        loginprocess.autoLogin(loginHandle);
    }

    private final Handler loginHandle = new Handler(Looper.myLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case Constant.LOGIN_SUCCESS:// 登陆成功
                    login = false;
                    UserLogin loginSuccess = (UserLogin) msg.obj;
                    handlerLoginResult(loginSuccess);
                    AppStatusManager.appStatusManager.getRoomInfo();
                    startService(new Intent(GWLoginActivity.this,MqttService.class));
                    break;
                case Constant.LOGIN_FAIL:// 登陆失败
                    login = false;
                    String loginErrorMsg = (String) msg.obj;
                    if (TextUtils.isEmpty(loginErrorMsg)) {
                        loginErrorMsg = "账号或密码错误";
                    }

                    isLogining = false;
                    LoginModel.instance().loginFail();
                    SharedPreferencesUtils.getInstance().setLoginUid(GWLoginActivity.this,"");
                    SharedPreferencesUtils.getInstance().setLoginAccount(GWLoginActivity.this,"");
                    if (isAutoLogin){
                        ToastUtil.show(GWLoginActivity.this, "登录信息已过期,请重新登录");
                        Intent intent = new Intent(GWLoginActivity.this,GWLoginActivity.class);
                        startActivity(intent);
                        finish();
                    }else {
                        submitBtn.setEnabled(true);
                        submitBtn.setText("确认登录");
                        ToastUtil.show(GWLoginActivity.this, loginErrorMsg);
                    }
                    break;
            }
            return false;
        }
    });

    private void loginSuccess(){
        LoginModel.instance().loginSuccess(true, true, AppStatusManager.getInstance().userLogin);
        Intent intent = new Intent(this,GWChooseAccountActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("userLogin",AppStatusManager.getInstance().userLogin);
        intent.putExtra("bundle",bundle);
        startActivity(intent);
        finish();
    }

    /**
     * 登陆成功
     */
    protected void handlerLoginResult(UserLogin loginSuccess) {
        GWLog.w(TAG, "Account = " + loginSuccess.getUserName());
        GWGameManager.getInstance().userLogin = loginSuccess;
        if ("1".equals(loginSuccess.getLoginStatus())) {
            loginSuccess();
        } else {
            LoginModel.instance().loginFail();
        }
    }


    private final Handler getCodeHeader = new Handler(Looper.myLooper()) {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mcTipDialog != null){
                mcTipDialog.dismiss();
            }
            switch (msg.what) {
                case Constant.VERIFYCODE_REQUEST_SUCCESS:
                    ToastUtil.show(GWLoginActivity.this, "发送成功");
                    startTimer();
                    break;
                case Constant.VERIFYCODE_REQUEST_FAIL:
                    getCodeBtn.setEnabled(true);
                    //getResources().getDrawable(R.drawable.gw_login_button_bg));
                    getCodeBtn.setBackgroundResource(GWInflaterUtils.getDrawable(GWLoginActivity.this,"gw_login_button_bg"));
                    getCodeBtn.setTextColor(Color.parseColor("#ffffff"));
                    String regErrorMsg = (String) msg.obj;
                    if (com.gwsdk.paysdk.utils.TextUtils.isEmpty(regErrorMsg)) {
                        regErrorMsg = "发送失败";
                    }
                    ToastUtil.show(GWLoginActivity.this, regErrorMsg);
                    break;
            }
        }
    };


    private Boolean checkLogin(String str_account, String str_password) {
        if (TextUtils.isEmpty(str_account)) {
            ToastUtil.show(this, "请输入账号");
            return false;
        }
        int length = str_account.trim().length();
        if (length < 6) {
            ToastUtil.show(this, "账号格式不正确");
            return false;
        }
        if (TextUtils.isEmpty(str_password)) {
            ToastUtil.show(this, "请输入密码");
            return false;
        }
        if (!isRegularAcc(str_password)) {
            ToastUtil.show(this, "密码格式不正确");
            return false;
        }
        return true;
    }

    private boolean isRegularAcc(String account) {
        String reg = Constant.REGULAR_ACCOUNT;
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher_acc = pattern.matcher(account);
        boolean b_acc = matcher_acc.matches();
        if (!b_acc) {
            return false;
        }
        return true;
    }

    private void startTimer(){
        getCodeBtn.setEnabled(false);
        getCodeBtn.setTextColor(Color.parseColor("#666666"));
        downTimer = new CountDownTimer(60 * 1000,1000) {
            @Override
            public void onTick(long l) {
                String value = String.valueOf((int) (l / 1000));
                getCodeBtn.setText(String.format("重新获取(%s)",value));
            }
            @Override
            public void onFinish() {
                downTimer.cancel();
                downTimer = null;
                getCodeBtn.setEnabled(true);
                getCodeBtn.setText("获取验证码");
                getCodeBtn.setTextColor(Color.parseColor("#ffffff"));
                //getResources().getDrawable(R.drawable.gw_login_button_bg));
                getCodeBtn.setBackgroundResource(GWInflaterUtils.getDrawable(GWLoginActivity.this,"gw_login_button_bg"));
            }
        };
        downTimer.start();
    }

    @Override
    public void onBackPressed() {
        if (isAutoLogin){
            super.onBackPressed();
        }

        if (downTimer != null){
            downTimer.cancel();
            downTimer = null;
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0,GWInflaterUtils.getIdByName(this,"anim","gw_scale_out"));//R.anim.gw_scale_out);
        unregisterReceiver(authLoginBroadcastReceiver);
        isResisterBroadcast = false;
        if (downTimer != null){
            downTimer.cancel();
            downTimer = null;
        }
    }


    private void ComeOutType() {
        Window window = getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        window.setDimAmount(0f); //设置背景透明度   0~1
        overridePendingTransition(GWInflaterUtils.getIdByName(this,"anim","gw_scale_in"),0);

    }
}
